<template>
  <d2-container>
    <el-form :model="FormSearch" status-icon label-width="100px" class="demo-ruleForm">
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="条件查找" prop="good">
            <el-input
              type="text"
              v-model="FormSearch.good"
              placeholder="请输入姓名"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="searchClick()">查询</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- 数据表格 -->
    <d2-crud
      ref="d2Crud"
      edit-title="编辑"
      add-title="添加商户账号"
      :columns="columns"
      :data="data"
      :rowHandle="rowHandle"
      :edit-template="editTemplate"
      :add-template="addTemplate"
      :add-rules="addRules"
      :edit-rules="editRules"
      :form-options="formOptions"
      :pagination="page"
      :loading="loading"
      @dialog-open="handleDialogOpen"
      @row-edit="handleRowEdit"
      @row-add="handleRowAdd"
      @dialog-cancel="handleDialogCancel"
      @custom-emit-1="addStock"
      @custom-emit-2="delGood"
      @custom-emit-3="setAuth"
      @pagination-current-change="paginationCurrentChange"
    >
    <el-button slot="header" style="margin-bottom: 5px;" @click="addRow">添加商户账号</el-button>
    </d2-crud>
  </d2-container>
</template>

<script>
import {
  deleteAccount,
  getUptown,
  updateAccount,
  getManagement,
  getUptownBuilding,
  getAccount,
  addAccount
} from "@/api/goods/index";
import util from "@/libs/util.js";

export default {
  data() {
    return {
      // 弹出层
      dialogFormVisible: false,
      // authority 为弹出层权限
      Eauthority: '',
      loading: false,
      type: [
        {
          value: '0',
          label: '管理员'
        },
        {
          value: '1',
          label: '员工'
        },
        {
          value: '2',
          label: '用户'
        },
      ],
      // 小区信息 单选
      housId: '',
      housInfo: [],
      // 小区信息 多选
      housManyId: [],
      housManyInfo: [],
      // 楼栋信息
      floorId: [],
      floorInfo: [],
      // 管理信息
      manageId: '',
      manageInfo: [],
      typeId: '',
      // 搜索数据
      FormSearch: {
        good: ""
      },
      // 字段名称
      columns: [
        { 
          title: "账号",
          key: "account",
          align: "center"
        },
        {
          title: "姓名",
          key: "name",
          align: "center"
        },
        /* {
          title: "商户代码",
          key: "MERCHANTID",
          align: "center"
        },
        {
          title: "分行代码",
          key: "BRANCHID",
          align: "center"
        },
        {
          title: "柜台代码",
          key: "POSID",
          align: "center"
        },
        {
          title: "建行密钥",
          key: "KEYCCB",
          align: "center"
        },
        {
          title: "查询密钥",
          key: "REMARK",
          align: "center"
        }, */
      ],
      // 列表数据
      data: [],
      // 操作列数据
      rowHandle: {
        align: "center",
        width: 380,
        custom: [
          /* {
            text: "生成订餐地址",
            type: "primary",
            size: "mini",
            emit: "custom-emit-3",
          }, */
          {
            text: "重置密码",
            type: "primary",
            size: "mini",
            emit: "custom-emit-1"
          },
          {
            text: "删除",
            type: "danger",
            size: "mini",
            emit: "custom-emit-2"
          },
        ],
        edit: {
          icon: "el-icon-edit",
          text: "编辑",
          size: "small"
        },
      },
      addTemplate: {
        name: {
          title: "姓名",
          value: ""
        },
        account: {
          title: "账号",
          value: ""
        },
        pwd: {
          title: "密码",
          value: ""
        },
        merchantid: {
          title: "商户代码",
          value: ""
        },
        branchid: {
          title: "分行代码",
          value: ""
        },
        posid: {
          title: "柜台代码",
          value: ""
        },
        keyccb: {
          title: "建行密钥",
          value: ""
        },
        remark: {
          title: "查询密钥",
          value: ""
        },
      },
       addRules: {
        name: [ { required: true, message: '请输入姓名', trigger: 'blur' } ],
        /* account: [ { required: true, trigger: 'blur', 
        validator: (rule, value) => {
          return new Promise((resolve, reject) => {
            if (value === '') {
              reject("请输入账号");  // reject with error message
            } else if (!(/^1[1234567890]\d{9}$/.test(value))) {
              reject("请输入正确的手机号为账号");
            } else {
              resolve()
            }
          });
        } } ], */
        account: [ { required: true, message: '请输入账号，可为手机号或者邮箱', trigger: 'blur' } ],
        password: [ { required: true, message: '请输入密码', trigger: 'blur' } ],
        authority: [ { required: true, message: '请选择权限等级', trigger: 'blur' } ]
      },
      editTemplate: {
        name: {
          title: "姓名",
          value: ""
        },
        MERCHANTID: {
          title: "商户代码",
          value: ""
        },
        BRANCHID: {
          title: "分行代码",
          value: ""
        },
        POSID: {
          title: "柜台代码",
          value: ""
        },
        KEYCCB: {
          title: "建行密钥",
          value: ""
        },
        REMARK: {
          title: "查询密钥",
          value: ""
        },
      },
      editRules: {
        name: [ { required: true, message: '请输入姓名', trigger: 'blur' } ],
      },
      formOptions: {
        labelWidth: "80px",
        labelPosition: "left",
        saveLoading: false
      },
      // 分页数据
      page: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      }
    };
  },
  created() {
    let params = {
      page: this.page.pageIndex,
      limit: this.page.pageSize
    };
    this.init(params);
  },
  methods: {
    // 初始化身体数据列表
    init(params) {
      this.loading = true
      params.typecode = 1
      getAccount(params)
        .then(res => {
          if (res.success) {
            this.data = res.rows || [];
            this.page.total = res.total;
          }
          this.loading = false
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err);
        });
    },

    // 普通的新增
    addRow() {
      this.$refs.d2Crud.showDialog({
        mode: "add"
      });
    },

    // 新增成功
    handleRowAdd(row, done) {
      this.formOptions.saveLoading = true;
      console.log(row)
      let params = row;
      params.typecode = 1
      addAccount(params)
        .then(res => {
          console.log(res);
          if (res.success) {
            this.$message({
              message: "添加成功",
              type: "success"
            });
          }

          // done可以传入一个对象来修改提交的某个字段
          done();
          // 保存按钮的loading状态
          this.formOptions.saveLoading = false;
          // 重新加载列表
          let params = {
            page: this.page.pageIndex,
            limit: this.page.pageSize,
          };
          this.init(params);
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 分页数改变，调用
    paginationCurrentChange(pageIndex) {
      let params = {
        limit: this.page.pageSize,
        name: this.FormSearch.good
      };
      params.page = this.page.pageIndex = pageIndex;
      params.type = this.typeId;
      this.init(params);
    },

    // 选择单个小区出现楼栋
    housChange(val) {
      let params = {
        page: 1,
        limit: 9999999,
        belongId: val
      };
      getUptownBuilding(params)
        .then(res => {
          if (res.success) {
            let zopt = []
              res.rows.map(item => {
                let opt = {
                  value: item.id,
                  label: item.name,
                }
                zopt.push(opt)
              })
              this.floorInfo = zopt
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
      console.log(val)
    },

    // 生成订餐地址
    setAuth({ index, row }) {
      this.Eauthority = row.authority
      this.role_id = row.role_id
      // 获取员工权限
      let params = {
        roleId: row.role_id
      }
      getManagement(params)
        .then(res => {
          if (res.success) {
            let zopt = []
            res.rows.map(item => {
              let opt = {
                value: item.id,
                label: item.xqname
              }
              zopt.push(opt)
            })
            this.manageInfo = ''
            this.manageInfo = zopt
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
      this.dialogFormVisible = true
    },

    // 条件查询搜索
    searchClick() {
      let params = {
        page: 1,
        limit: 10
      };
      params.name = this.FormSearch.good;
      this.init(params);
    },

    // 重置查询
    resetForm() {
      this.FormSearch.good = "";
      let params = {
        page: 1,
        limit: 10
      };
      this.init(params);
    },

    // 点击编辑时 mode 为编辑或者添加，row为点击这一行数据
    handleDialogOpen({ mode, row }) {
    },

    // 编辑提交
    handleRowEdit({ index, row }, done) {
      // 保存按钮的loading状态
      this.formOptions.saveLoading = true;
      let params = {};
      params.id = row.id;
      params.merchantid = row.MERCHANTID;
      params.branchid = row.BRANCHID;
      params.name = row.name;
      params.posid = row.POSID;
      params.keyccb = row.KEYCCB;
      params.remark = row.REMARK;
      updateAccount(params)
        .then(res => {
          if (res.success) {
            this.$message({
              message: "编辑成功",
              type: "success"
            });
          }
          // done可以传入一个对象来修改提交的某个字段
          done();
          // 保存按钮的loading状态
          this.formOptions.saveLoading = false;
          // 重新加载列表
          let params = {
            page: this.page.pageIndex,
            limit: this.page.pageSize
          };
          params.classLevel = 1;
          this.init(params);
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 取消编辑
    handleDialogCancel(done) {
      /* this.$message({
        message: "取消编辑",
        type: "warning"
      }); */
      done();
    },

    // 删除商品
    delGood({ index, row }) {
      let params = {
        id: row.id,
      }
      this.$confirm(`此操作将删除账号, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteAccount(params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: "删除成功",
                  type: "success"
                });
                // 重新加载列表
                let params = {
                  page: this.page.pageIndex,
                  limit: this.page.pageSize,
                };
                this.init(params);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(err => {});
    },

    // 重置密码
    addStock({ index, row }) {
      let params = {
        id: row.id,
        pwd: 111111
      }
      this.$confirm(`此操作将重置密码, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateAccount(params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: "重置成功，密码为111111",
                  type: "success"
                });
                // 重新加载列表
                let params = {
                  page: this.page.pageIndex,
                  limit: this.page.pageSize,
                };
                this.init(params);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(err => {});
    },
  }
};
</script>
<style lang="scss" scoped>
</style>
